﻿using System;
using TEngine;
using UnityEngine;
using UnityEngine.UI;

public class GrayImage : Image
{
    private static Material m_SharedMat;
    private Material m_ownedMat;
    private Material changedMat;

    public override Material material
    {
        get
        {
            initShareMat();

            if (changedMat != null)
            {
                return changedMat;
            }
            else if (m_ownedMat != null)
            {
                return m_ownedMat;
            }
            else if (m_SharedMat != null)
            {
                return m_SharedMat;
            }

            return defaultMaterial;
        }
        set
        {
            initShareMat();
            changedMat = value;
            if (value != null && value.shader != null && m_SharedMat.shader.name == value.shader.name)
            {
                changedMat = null;
            }

            SetMaterialDirty();
        }
    }

    private void initShareMat()
    {
        if (m_SharedMat == null)
        {
            Shader s = GameModule.Resource.LoadAsset<Shader>("Assets/AssetRaw/Shaders/UI-GrayImage");
            if (s == null)
            {
                Log.Error("load shader asset failed11");
                return;
            }
            m_SharedMat = new Material(s);
        }
    }

    public void SetGray(bool gray, float alpha = 1f)
    {
        if (gray)
            color = new Color(0, 0, 0, alpha);
        else
            color = new Color(1, 1, 1, alpha);
    }

    public void SetBrightness(float brightness)
    {
        material.SetFloat("_Brightness", brightness);
    }

    public void InitOwnedMat()
    {
        if (m_ownedMat == null)
        {
            Shader s = GameModule.Resource.LoadAsset<Shader>("Assets/AssetRaw/Shaders/UI-GrayImage");
            m_ownedMat = new Material(s);
        }
    }
}